package register

import (
	"New-lesson-part2/internal"
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
)

type IRegister interface {
	WebRegister(host, name, id string, port int, tags []string) error
	DeRegister(serviceId string) error
}
type ConsulRegisTry struct {
	Host string
	Port int
}

func NewConsulRegistry(host string, port int) ConsulRegisTry {
	return ConsulRegisTry{
		Host: host,
		Port: port,
	}
}

func (cr ConsulRegisTry) WebRegister(host, name, id string, port int, tags []string) error {
	defaultConfig := consulapi.DefaultConfig()
	consulRegistry := NewConsulRegistry(internal.AppConf.ConsulConfig.Host, internal.AppConf.ConsulConfig.Port)
	ConsulAddress := fmt.Sprintf("%s:%d", consulRegistry.Host, consulRegistry.Port)
	defaultConfig.Address = ConsulAddress
	client, err := consulapi.NewClient(defaultConfig) //生成consul客户端
	if err != nil {
		return err
	}
	registration := &consulapi.AgentServiceRegistration{
		ID:      id,
		Name:    name,
		Tags:    tags,
		Port:    port,
		Address: host,
	}
	//serverAddr := fmt.Sprintf("http://%s:%d/health", registration.Address, registration.Port)
	//check := &consulapi.AgentServiceCheck{
	//	Interval:                       "1s",
	//	Timeout:                        "3s",
	//	HTTP:                           serverAddr,
	//	DeregisterCriticalServiceAfter: "10s",
	//}

	//registration.Check = check
	return client.Agent().ServiceRegister(registration)
}

func (cr ConsulRegisTry) DeRegister(serviceId string) error {
	defaultConfig := consulapi.DefaultConfig()
	ConsulAddress := fmt.Sprintf("%s:%d", internal.AppConf.ConsulConfig.Host, internal.AppConf.ConsulConfig.Port)
	defaultConfig.Address = ConsulAddress
	client, err := consulapi.NewClient(defaultConfig) //生成consul客户端
	if err != nil {
		return err
	}
	return client.Agent().ServiceDeregister(serviceId)

}
